//Author: Zhengwei Pu & Lu Xu
// Term project for ECE59500

//If run this game in an operation system based on Chinese, the buttons of the dialog will show Chinese!
//
//But if in English OS, it also works well!
//
//The language of this game is based on your operation system. 


import java.awt.Color;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.Timer;
import javax.swing.border.Border;
import javax.swing.border.EtchedBorder;
import javax.swing.JOptionPane;
import java.sql.*;

/*
 * ControlPanel Class
 */
public class ControlPanel extends JPanel{
	private ImagePanel imagePanel;  //A panel contains snake
	private LevelScorePanel levelScorePanel;    //a panel show the level and score
	private ButtonPanel buttonPanel;    //Button panel,contains of start buttorn , control the game
	private SnakeGame game;
        private Record record;
        Statement st; 
        
        Connection conn=dbutil.getconnection();
	/*
	 * Constructor Method TO create controlpanel
	 */
	public ControlPanel(SnakeGame game){
		this.game = game;
	   	setLayout(new GridLayout(3,1));//set the layout manager as gridlayout
	   	imagePanel = new ImagePanel();
	   	levelScorePanel = new LevelScorePanel();
	   	buttonPanel = new ButtonPanel();
	   	add(imagePanel);
	   	add(levelScorePanel);
	   	add(buttonPanel);
                this.addKeyListener(new ControlKeyListener());//add keyboard lister,use the up,down,left,right key to control the game
	}


	/*
	 * ImagePanel
	 */
	private class ImagePanel extends JPanel{
		 private Border border = new EtchedBorder(EtchedBorder.RAISED,Color.white,Color.lightGray);
		 private ImageIcon snakeImage = new ImageIcon("snake.jpg");
		 
		 public ImagePanel(){
			 setBorder(border);//add boarder
		 }
		 
		 public void paintComponent(Graphics g){//paint snake component
			super.paintComponent(g);
			snakeImage.paintIcon(this, g, 0, 0);
		 }
	}

	/*
	 * Panel to show score and level
	 */
	private class LevelScorePanel extends JPanel{
		private JLabel scoreLabel = new JLabel("Score");
		private JLabel levelLable = new JLabel("Level");
		private Timer timer;//Time calculator, it will start a thread to update the scroe and level
		private JTextField scoreTextField,levelTextField;
                private Border border = new EtchedBorder(EtchedBorder.RAISED,Color.white,Color.lightGray);
	   
		public LevelScorePanel(){
			scoreTextField = new JTextField();
			levelTextField = new JTextField();
			
			scoreTextField.setEditable(false);
			levelTextField.setEditable(false);
			
			setLayout(new GridLayout(4,1));
			add(scoreLabel);
			add(scoreTextField);
			add(levelLable);
			add(levelTextField);
			setBorder(border);
			timer = new Timer(200, new ActionListener() {//set actionlister for the fixed time to update score and levle
					public void actionPerformed(ActionEvent event) {
						levelTextField.setText("" + game.getLevel());
						scoreTextField.setText("" + game.getScore());
					}
				});
			timer.start();
		}
	}

	/*
	 * Buttons' panel
	 */
	private class ButtonPanel extends JPanel{
                private JButton gameidrecordButton;
		private JButton playButton,stopButton,pauseOrResumeButton;
		private JButton turnEasierButton,turnHarderButton;
		private Border border = new EtchedBorder(EtchedBorder.RAISED,Color.white,Color.lightGray);
		private Timer timer;
                private String dbstring;
		private String gameid;

                
		public ButtonPanel(){
			playButton = new JButton("Start");
			stopButton = new JButton("Stop");
			pauseOrResumeButton = new JButton("Pause");
			turnEasierButton = new JButton("Easy");
			turnHarderButton = new JButton("Hard");
			gameidrecordButton=new JButton("Record");   
                         
			setLayout(new GridLayout(6,1));
			add(playButton);
			add(stopButton);
			add(pauseOrResumeButton);
			add(turnEasierButton);
			add(turnHarderButton);
                        add(gameidrecordButton);

			setBorder(border);
			//add laybutton keylistener
			playButton.addActionListener(new ActionListener(){
				public void actionPerformed(ActionEvent e) {
				    	game.startGame();//start the game
				    	playButton.setEnabled(false);//disanble the playbutton
				    	stopButton.setEnabled(true);//enable stopButton
				        ControlPanel.this.requestFocus();//ControlPanel catch focus again
				}
			});
			
			 stopButton.addActionListener(new ActionListener(){
				public void actionPerformed(ActionEvent e) {
				    	game.stopGame();
				    	stopButton.setEnabled(false);
				        ControlPanel.this.requestFocus();
				}
			});
			
			pauseOrResumeButton.addActionListener(new ActionListener(){
				public void actionPerformed(ActionEvent e) {
					if(pauseOrResumeButton.getText().equals("Pause")){
						game.pauseGame();//pause the game
						pauseOrResumeButton.setText("Resume");//switch the pause and resume button
					}else{
						game.resumeGame();//resume the game
						pauseOrResumeButton.setText("Pause");
					}
					ControlPanel.this.requestFocus();//ControlPanel catch focus again
				}
			});
			
			turnEasierButton.addActionListener(new ActionListener(){
				public void actionPerformed(ActionEvent e) {
					game.decLevel();//lower the level
					ControlPanel.this.requestFocus();
				}
			});
			turnHarderButton.addActionListener(new ActionListener(){
				public void actionPerformed(ActionEvent e) {
					game.incLevel();//upgrade the level
					ControlPanel.this.requestFocus();
				}
			});

                        gameidrecordButton.addActionListener(new ActionListener(){
				public void actionPerformed(ActionEvent e) {
                                    game.pauseGame();
                                String gameid = JOptionPane.showInputDialog( "Please type your game ID ");
                                PreparedStatement ps = null;
                                //String insertid = gameid+game.getScore()+game.getLevel(); 
                                //TO DO: add the function to check if the gameid has already exist in the db
                                int gamescore=game.getScore();
                                String query="INSERT INTO Snakedb VALUES(?,?)";
                                try {
                                    ps = conn.prepareStatement(query);    
                                    ps.setString(1,gameid);
                                    ps.setInt(2, gamescore);
                                    int temp=ps.executeUpdate();
                                    //st = conn.createStatement();
                                    //st.executeUpdate(query);
                                } 
                                catch(SQLException ex) {
                                        System.err.println("SQLException: " + ex.getMessage());
                                    }                                      
				}
			});
                        
			timer = new Timer(200, new ActionListener() {//dingshiqi listener,enbale the playButton when the game stopped
				public void actionPerformed(ActionEvent event) {
					if(game.isGameOver()){
						playButton.setEnabled(true);
					}
				}
			});
			timer.start();
		}
	}

	/*
	 * Key ControlListener
	 */
	private class ControlKeyListener extends KeyAdapter{
		public void keyPressed(KeyEvent ke) {
			int currentDirection = game.getSnakeDirection();
			if(game.isPlaying()){
				switch(ke.getKeyCode()){
					case KeyEvent.VK_DOWN:
						if(currentDirection != Utils.UP)//only one direction
							game.changeSnakeDirection(Utils.DOWN);//change the snake's forward direction
						break;
					case KeyEvent.VK_UP:
						if(currentDirection != Utils.DOWN)
							game.changeSnakeDirection(Utils.UP);
						break;
					case KeyEvent.VK_LEFT:
						if(currentDirection != Utils.RIGHT)
							game.changeSnakeDirection(Utils.LEFT);
						break;
					case KeyEvent.VK_RIGHT:
						if(currentDirection != Utils.LEFT)
							game.changeSnakeDirection(Utils.RIGHT);
						break;
				}
			}
		}
	}
}
